package com.practice.backend.Controller;

import com.practice.backend.Common.Result;
import com.practice.backend.Entity.Goods;
import com.practice.backend.Entity.Order;
import com.practice.backend.Entity.OrderWithName;
import com.practice.backend.Repository.GoodsRepository;
import com.practice.backend.Repository.OrderRepository;
import com.practice.backend.Repository.UserRepository;
import com.practice.backend.Repository.WarehouseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/order")
public class OrderController {

@Autowired
private OrderRepository orderRepository;
@Autowired
private GoodsRepository goodsRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private WarehouseRepository warehouseRepository;




@RequestMapping("/findAll")
public Result findAll(){
    List<OrderWithName> orderWithNames = new ArrayList<>();
    List<Order> orders = orderRepository.findAll();
    for (Order order : orders) {

        String goodsName = goodsRepository.finNameById(order.getGoodsId());
        String userName = userRepository.findById(order.getUserId()).get().getUsername();
        OrderWithName orderWithName = new OrderWithName(
                order.getCost(),
                order.getCustomerName(),
                order.getCustomerPhone(),
                order.getDealCount(),
                order.getDealPurpose(),
                order.getDealTime(), // 确保 dealTime 被正确传递
                order.getGoodsId(),
                goodsName,
                order.getGoodsQuality(),
                order.getId(),
                order.getType(),
                order.getUserId(),
                order.getWareHouseId(),
                userName
        );
        orderWithNames.add(orderWithName);
    }
    return Result.success(true,"查询成功",orderWithNames.size(),orderWithNames);
    }


    @PostMapping("/add")
    public Result add(@RequestBody OrderWithName orderWithName) {
        String goodsName = orderWithName.getGoodsName();
        Integer goodsQuality = orderWithName.getGoodsQuality();
        Integer warehouseId = orderWithName.getWareHouseId();

        // 检查仓库是否存在
        if (!warehouseRepository.existsById(orderWithName.getWareHouseId())) {
            System.out.println("仓库不存在");
            return Result.error(false, "仓库不存在", null, null);
        }
        else
            System.out.println("仓库存在");



        Goods currentGoods = goodsRepository.findByNameAndQualityAndWarehouse(goodsName, goodsQuality, warehouseId);


        // 售出订单处理
        if (orderWithName.getType().equals("售出")) {
            // 检查商品是否存在
            if (currentGoods == null) {
                return Result.error(false, "商品不存在于仓库中", null, null);
            }
            // 检查库存是否充足
            if (currentGoods.getCount() < orderWithName.getDealCount()) {
                return Result.error(false, "仓库余货不足，当前存货数量：" + currentGoods.getCount(), null, null);
            }
            // 减少库存
            currentGoods.setCount(currentGoods.getCount() - orderWithName.getDealCount());
            goodsRepository.save(currentGoods);  // 更新库存
        }
        // 进货订单处理
        else {
            // 商品不存在则创建新商品
            if (currentGoods == null) {
                currentGoods = new Goods();
                currentGoods.setName(goodsName);
                currentGoods.setWeight(0.0);
                currentGoods.setVolume(0.0);
                currentGoods.setQuality(goodsQuality);
                currentGoods.setWareHouseId(orderWithName.getWareHouseId());
                currentGoods.setCount(orderWithName.getDealCount());  // 初始库存
            } else {
                // 商品存在则增加库存
                currentGoods.setCount(currentGoods.getCount() + orderWithName.getDealCount());
            }
            goodsRepository.save(currentGoods);  // 保存新商品或更新库存
        }

        // 创建订单记录（售出/进货都需要）
        Order order = new Order();
        // 订单信息
        order.setGoodsId(currentGoods.getId());  // 关联商品ID
        order.setCost(orderWithName.getCost());
        order.setWareHouseId(orderWithName.getWareHouseId());
        order.setType(orderWithName.getType());
        order.setCustomerName(orderWithName.getCustomerName());
        order.setCustomerPhone(orderWithName.getCustomerPhone());
        order.setDealCount(orderWithName.getDealCount());
        order.setDealPurpose(orderWithName.getDealPurpose());
        order.setGoodsQuality(orderWithName.getGoodsQuality());
        order.setUserId(orderWithName.getUserId());
        order.setDealTime(orderWithName.getDealTime());
        orderRepository.save(order);  // 保存订单
        return Result.success(true, "操作成功", 1, order);
    }
}
